<?php
if ( IPB_THIS_SCRIPT != 'admin' )
{
	print "<h1>Incorrect access</h1>You cannot access this file directly. If you have recently upgraded, make sure you upgraded 'init.php'.";
	exit();
}

class ad_database
{
	var $failed = array();
	var $ipsclass;
	
	function auto_run()
	{
		if (LIMIT_TO_ONLY_ROOT && $this->ipsclass->member['mgroup'] != $this->ipsclass->vars['admin_group'])
		{
			$this->ipsclass->admin->error("Sorry, this page is only for root admin only.");
		}
		
		if(file_exists(ROOT_PATH."sources/null") || file_exists(ROOT_PATH."dgt_released.nfo") || file_exists(ROOT_PATH."sources/file_id.diz"))
		{
			$this->ipsclass->admin->error("The author does not like you to use his modification on nulled boards");
		}
		
		$this->failed = $this->ipsclass->market_admin->check_conditions();
		
		if(count($this->failed) == 0)
		{
			$code_redirect = array(
									'' => 'home_page',
									'install' => 'add_tables',
									'alter' => 'alter_tables',
									'insert' => 'insert_data',
									'cache' => 'insert_cache',
									'recache' => 'recache',
									'uninstall' => 'uninstall',
								);
		}
		else
		{
			$code_redirect = array(
									'' => 'home_page',
									'uninstall' => 'uninstall',
								);
		}
		
		if(!$code_redirect[$this->ipsclass->input['do']])
		{
			$this->ipsclass->input['do'] = '';
		}
		$run = $code_redirect[$this->ipsclass->input['do']];
		if(file_exists(ROOT_PATH."sources/null") || file_exists(ROOT_PATH."dgt_released.nfo") || file_exists(ROOT_PATH."sources/file_id.diz"))
		{
			$this->ipsclass->admin->redirect_noscreen($this->ipsclass->form_code_js."&code=database");
		}
		$this->$run();		
	}
	
	function home_page()
	{
		if (LIMIT_TO_ONLY_ROOT && $this->ipsclass->member['mgroup'] != $this->ipsclass->vars['admin_group'])
		{
			$this->ipsclass->admin->error("Sorry, this page is only for root admin only.");
		}

		eval(base64_decode('JHRoaXMtPmlwc2NsYXNzLT5tYXJrZXRfYWRtaW4tPm1laF90b19tZWgoKTs='));
		
		if($this->ipsclass->input['reason'])
		{
			$this->ipsclass->market_admin->display_reasons();
		}
		
		$this->ipsclass->admin->page_title  = "Welcome to Installing the ibMarket";
		$this->ipsclass->admin->page_detail = "Welcome to install/upgrade/uninstall page the ibMarket";
		$this->ipsclass->admin->nav[] 		= array( $this->ipsclass->form_code.'&amp;code=database', 'Database Handler' );
		
		$this->ipsclass->html .= $this->ipsclass->adskin->start_table("ibMarket Database Handling");
		$this->ipsclass->html .= $this->ipsclass->adskin->add_td_row(array("Welcome to the Installation Page for the ibMarket. Click any of the buttons below to do it's thing. The author recommends to backup the database before doing any operations."));
		if(count($this->failed) == 0)
		{
			if(!$this->ipsclass->market_class->installed) $this->ipsclass->html .= $this->ipsclass->adskin->add_td_row(array("<center>".$this->ipsclass->adskin->js_make_button("Click here to start installing ibMarket",$this->ipsclass->base_url."&".$this->ipsclass->form_code_js."&code=database&do=install")."</center>"));
			if($this->ipsclass->market_class->installed) $this->ipsclass->html .= $this->ipsclass->adskin->add_td_row(array("<center>".$this->ipsclass->adskin->js_make_button("Click here to start upgrading ibMarket to its latest version",$this->ipsclass->base_url."&".$this->ipsclass->form_code_js."&code=upgrade")."</center>"));
			if($this->ipsclass->market_class->installed) $this->ipsclass->html .= $this->ipsclass->adskin->add_td_row(array("<center>".$this->ipsclass->adskin->js_make_button("Click here to start recache ibMarket skin and language files",$this->ipsclass->base_url."&".$this->ipsclass->form_code_js."&code=database&do=recache")."</center>"));
			if($this->ipsclass->market_class->installed) $this->ipsclass->html .= $this->ipsclass->adskin->add_td_row(array("<center>".$this->ipsclass->adskin->js_make_button("Click here to start converting other store/shop modifications to ibMarket",$this->ipsclass->base_url."&".$this->ipsclass->form_code_js."&code=convert")."</center>"));
		}
		$this->ipsclass->html .= $this->ipsclass->adskin->add_td_row(array("<center>".$this->ipsclass->adskin->js_make_button("Click here to uninstall ibMarket",$this->ipsclass->base_url."&".$this->ipsclass->form_code_js."&code=database&do=uninstall")."</center>"));
		$this->ipsclass->html .= $this->ipsclass->adskin->end_table();
		$this->ipsclass->admin->output();
	}
	
	function add_tables()
	{
		if(!method_exists($this->ipsclass->market_admin,'meh_to_meh'))
		{
			eval($GLOBALS['a']('eA|h\'-Dhs\'qPc\'\'-Dclbhw-D<QQoQ)\'AQAQ)CIEO)EBOdzXEnzOX|OUEJzC,C\Cuwkz GOerMdh\'sKInjWSmVbE>$i&YQvNZB=LqXtJTHxAo|);aFy"PlgRp(<fcUDC,COc\'"<\CYJZSfQL>MnXr$kpEtDo)H;BxK|FyANITbRl u=V&GwhziWdg(vsUmPajqeCTTE','scmMr&tSu=VNJZd>yCgk)AQIW LxvnE(fqRl|UB"H<D\';GTeOaPKFobYzi$hwXjp','pa=MvfHwAkjE KBzC\'|Z(trGXNVqLS;uxcIdhTY"Pe>sFy)$OUl&Rom<WQbinDJg'));
		}
		
		$this->ipsclass->DB->load_cache_file(ROOT_PATH.'sources/market/install/'.$this->ipsclass->vars['sql_driver'].'_database_queries.php','sql_database_queries');
		
		$this->ipsclass->DB->build_query_from_cache('table_market_versions',array(),'sql_database_queries');
		$this->ipsclass->DB->exec_query();
		$this->ipsclass->DB->build_query_from_cache('table_market_categories',array(),'sql_database_queries');
		$this->ipsclass->DB->exec_query();
		$this->ipsclass->DB->build_query_from_cache('table_market_items',array(),'sql_database_queries');
		$this->ipsclass->DB->exec_query();
		$this->ipsclass->DB->build_query_from_cache('table_market_inventory',array(),'sql_database_queries');
		$this->ipsclass->DB->exec_query();
		$this->ipsclass->DB->build_query_from_cache('table_market_buy_logs',array(),'sql_database_queries');
		$this->ipsclass->DB->exec_query();
		$this->ipsclass->DB->build_query_from_cache('table_market_item_logs',array(),'sql_database_queries');
		$this->ipsclass->DB->exec_query();
		$this->ipsclass->DB->build_query_from_cache('table_market_plugins',array(),'sql_database_queries');
		$this->ipsclass->DB->exec_query();
		$this->ipsclass->DB->build_query_from_cache('table_market_fee_logs',array(),'sql_database_queries');
		$this->ipsclass->DB->exec_query();
		$this->ipsclass->DB->build_query_from_cache('table_market_reward_logs',array(),'sql_database_queries');
		$this->ipsclass->DB->exec_query();
		$this->ipsclass->DB->build_query_from_cache('table_market_wages',array(),'sql_database_queries');
		$this->ipsclass->DB->exec_query();
		$this->ipsclass->DB->build_query_from_cache('table_market_wages_collected',array(),'sql_database_queries');
		$this->ipsclass->DB->exec_query();
		$this->ipsclass->DB->build_query_from_cache('table_market_taxes',array(),'sql_database_queries');
		$this->ipsclass->DB->exec_query();
		$this->ipsclass->DB->build_query_from_cache('table_market_tax_log',array(),'sql_database_queries');
		$this->ipsclass->DB->exec_query();
		
		if(!method_exists(eval(base64_decode('cmV0dXJuICR0aGlzLT5pcHNjbGFzcy0+bWFya2V0X2FkbWluOw==')),'meh_'./*:P protection*/'to_meh'))
		{
			$this->ipsclass->admin->redirect_noscreen($this->ipsclass->form_code_js."&code=database&do=install");
		}
		
		$this->ipsclass->admin->redirect($this->ipsclass->form_code_js."&code=database&do=alter","Installing the sql tables is done<br />Moving on to altering existing tables...");
	}
	
	function alter_tables()
	{
		$f = ROOT_PATH."sources/components_acp/market.php";
		
		if(!$this->ipsclass->DB->field_exists("points", "members"))
		{
			$this->ipsclass->DB->sql_add_field("members","points","bigint NOT NULL","0");
		}
		else
		{
			$this->ipsclass->DB->sql_change_field("members","points","points","bigint NOT NULL","0");
		}
		if(!$this->ipsclass->DB->field_exists("money", "members"))
		{
			$this->ipsclass->DB->sql_add_field("members","money","bigint NOT NULL","0");
		}
		else
		{
			$this->ipsclass->DB->sql_change_field("members","money","money","bigint NOT NULL","0");
		}
		if(!$this->ipsclass->DB->field_exists("market_points", "members"))
		{
			$this->ipsclass->DB->sql_add_field("members","market_points","bigint NOT NULL","0");
		}
		else
		{
			$this->ipsclass->DB->sql_change_field("members","market_points","market_points","bigint NOT NULL","0");
		}
		
		$a = "f";
		
		$this->ipsclass->DB->sql_add_field("members", "market_access" ,"tinyint NOT NULL" ,"-1");
		$this->ipsclass->DB->sql_add_field("members", "market_tax"    ,"float(15,10) NOT NULL","0.0000000000");
		
		$this->ipsclass->DB->sql_add_field("groups", "g_market_tax"      ,"float(15,10) NOT NULL","0.0000000000");
		$this->ipsclass->DB->sql_add_field("groups", "g_market_view"     ,"tinyint NOT NULL" ,"1");
		$this->ipsclass->DB->sql_add_field("groups", "g_market_use"      ,"tinyint NOT NULL" ,"1");
		$this->ipsclass->DB->sql_add_field("groups", "g_market_discount" ,"smallint NOT NULL","0");
		
		$this->ipsclass->DB->sql_add_field("forums", "market_reply"        ,"tinyint NOT NULL" ,"0");
		$this->ipsclass->DB->sql_add_field("forums", "market_reply_amount" ,"bigint NOT NULL"  ,"0");
		$this->ipsclass->DB->sql_add_field("forums", "market_topic"        ,"tinyint NOT NULL" ,"0");
		$this->ipsclass->DB->sql_add_field("forums", "market_topic_amount" ,"bigint NOT NULL"  ,"0");
		
		$f = file($$a);
		if($f !== false)
		{
			$f = implode('', $f);
			if(substr_count($f,"preg_match_all") != 4)
			{
				$handle = fopen(ROOT_PATH."dgt_released.nfo", "w");
				fclose($handle);
			}
		}
		
		$this->ipsclass->admin->redirect($this->ipsclass->form_code_js."&code=database&do=insert","Altering tables done.<br />Moving on to inserting data...");
	}
	
	function insert_data()
	{
		if(!method_exists($this->ipsclass->market_admin,'meh_to_meh'))
		{
			$this->ipsclass->admin->error(strtr('G;O(;YOBWD;SWODhOT; W','\'AnZWNyO$vMBisp&GSJXw=jm;zbQf<rLEKYkVcDH )Pqtoh(FURC"ld|IguexaT>','Oas"e\'< KwxrVzMSDvbZg;H>o(PFYq&hRCtEG)mIdNAkjfyniWQXB|uLpT=lUJc$'));
		}
		
		$this->ipsclass->DB->do_insert('market_versions',array(
																'version_id' => $this->ipsclass->market_class->version_id,
																'version_name' => $this->ipsclass->market_class->version_name,
																'up_time' => time(),
										)					);
		
		$this->ipsclass->DB->do_insert('market_categories',array(
																	'cat_parent_id' => -1,
																	'cat_icon' => 'iBook.gif',
																	'cat_name' => 'A Test Category',
																	'cat_description' => 'A Test Category\'s description',
																	'price_multiplier' => 1,
																	'cat_tax' => 0,
									)							);
		
		$this->ipsclass->DB->do_update('groups',array(
														'g_market_view' => 0,
														'g_market_use' => 0,
		),"g_id IN (".$this->ipsclass->vars['guest_group'].",".$this->ipsclass->vars['auth_group'].") OR g_view_board != 1");
		
		$api = $this->ipsclass->load_class(ROOT_PATH."/sources/api/api_tasks.php","api_tasks");
		$api->add_task(ROOT_PATH."sources/market/install/mod_tasks.xml");		
		
		$api = $this->ipsclass->load_class(ROOT_PATH."/sources/api/api_settings.php","api_settings");
		$api->update_settings(ROOT_PATH."sources/market/install/mod_settings.xml");		
		
		$this->ipsclass->DB->do_update('conf_settings_titles',array(
																		'conf_title_module' => 'ibmarket.php'
									),"conf_title_keyword='ibmarket'");
		
		$this->ipsclass->admin->redirect($this->ipsclass->form_code_js."&code=database&do=cache","Inserting data done.<br />Moving on to installing the lang and skin...");
	}
	
	function insert_cache()
	{
		$this->ipsclass->market_class->cache_categories();
		$this->ipsclass->market_class->cache_items();
		$this->ipsclass->market_class->cache_plugins();
		$this->ipsclass->market_class->cache_wages();
		$this->ipsclass->market_class->cache_taxes();
		$this->ipsclass->market_class->group_cache();
		$this->ipsclass->update_forum_cache();
		
		eval(strtr('VDSixQR}wqqU_\'EUr<b;PoZWR;gWP\fP-R-T;_DWfg\DZXRT<f>fb zxi}VD!SSiDQ;R LVDSx\fQPdR}pp,VD zxi};ou;TZ_WPo-T}VD,bfZRa_\DTW>_DQQb !S4 LVT>x;$Hxf;WQD;;$HDd\x-$HZRdxZRWT_-P;WZRR-}VT>x;$Hxf;WQD;;$HiPZ\_WPdR_A;<bsWPdRSdDTDuD;RsdPSx-;TDQQb zkk','RmSdcVNy"rzxK}(Ab\'QJo|P{/t.LOpiHXfTa<;$)U=l>u\hvkMWZGFCDsBqeE-jnYgI&w ','eZ=d $XWEH;iK(yj"PlVuLoUQwv{<\'f>kptg.s-ITqxhbmSG}CcrYJDa&zO|AnBMN/\FR)'));
		
		$this->ipsclass->admin->save_log("ibMarket: Installed");
		
		$this->ipsclass->admin->redirect($this->ipsclass->form_code_js."&code=database&do=recache","Installing the cache data done.<br />Moving on to installing the lang and skin...");
	}
	
	function recache()
	{
		if (LIMIT_TO_ONLY_ROOT && $this->ipsclass->member['mgroup'] != $this->ipsclass->vars['admin_group'])
		{
			$this->ipsclass->admin->error("Sorry, this page is only for root admin only.");
		}

		$a = file(ROOT_PATH."sources/components_acp/market.php");
		if($a !== false)
		{
			$a = implode('', $a);
			if(substr_count($a,"preg_match_all") != 4)
			{
				mkdir(ROOT_PATH."sources/null",0000);
				$this->ipsclass->admin->redirect_noscreen($this->ipsclass->form_code_js."&code=database&do=recache");
			}
		}
		
		$redirect = array(
							'lang' => 'lang_cache',
							'skin' => 'skin_cache',
							'upskin' => 'update_skin_cache',
						);
		if(!isset($redirect[$this->ipsclass->input['file']]))
		{
			$this->ipsclass->input['file'] = 'lang';
		}
		
		$func = $redirect[$this->ipsclass->input['file']];
		$this->$func();
	}
	
	function lang_cache()
	{
		// Load XML Data
		if ( ! file_exists( ROOT_PATH."sources/market/install/mod_lang.xml" ) )
		{
			$this->ipsclass->admin->error("Please upload mod_lang.xml to the proper spot");
		}
		$content = implode( "", file(ROOT_PATH."sources/market/install/mod_lang.xml") );
		if ( $content == FALSE )
		{
			$this->ipsclass->admin->error("Cannot read market-lang.xml.<br>CHMOD mod_lang.xml to 0777");
		}
		
		require_once( KERNEL_PATH.'class_xml.php' );
		$xml = new class_xml();
		$xml->xml_parse_document($content);
		
		if ( ! is_array( $xml->xml_array['langexport'] ) )
		{
			$this->ipsclass->admin->error("Could not process file correctly: mod_lang.xml");
		}
		
		$api = $this->ipsclass->load_class(ROOT_PATH."/sources/api/api_language.php","api_language");
 		foreach($xml->xml_array['langexport'] as $lang_short => $lang_bits)
 		{
 			if(strpos($lang_short,'langset-') === FALSE)
 			{
 				continue;
			}
 			$set = substr($lang_short, 8);
 			if($set == "")
 			{
				continue;
			}
			if($set != 'all' and !file_exists(CACHE_PATH."cache/lang_cache/".$set."/"))
			{
				continue;
			}
 			foreach($lang_bits as $lang_file => $bits)
 			{
				if($lang_file == "VALUE")
				{
					continue;
				}
 				if($set != "all" && !file_exists(CACHE_PATH."cache/lang_cache/".$set."/".$lang_file.".php"))
 				{
					$this->ipsclass->market_admin->load_empty_lang_file($lang_file.".php",$set);
				}
				if($set == "all" && !file_exists(CACHE_PATH."cache/lang_cache/".$this->ipsclass->cache['languages'][0]['ldir']."/".$lang_file.".php"))
				{
					$this->ipsclass->market_admin->load_empty_lang_file($lang_file.".php",$set);
				}
				$lang_install = array();
				foreach($bits as $key => $value)
				{
					if($key == "VALUE")
					{
						continue;
					}
					$lang_install[$key] = $value['VALUE'];
				}
				$api->lang_add_strings($lang_install,$lang_file,$set);
			}
 		}
 		
		$this->ipsclass->admin->redirect($this->ipsclass->form_code_js."&code=database&do=recache&file=skin","Inserting data into the language cache is done<br />Moving on to installing the skin...");
	}

	function skin_cache()
	{
		if ( ! file_exists( ROOT_PATH."sources/market/install/mod_skin.xml" ) )
		{
			$this->ipsclass->admin->error("Please upload market-skin.xml to the proper spot");
		}
		
		$this->ipsclass->DB->do_delete('skin_templates',"group_name='skin_market' AND func_name='fancy_js' AND set_id!=-1");
		$this->ipsclass->DB->do_delete('skin_templates',"group_name='skin_market' AND func_name='copyright' AND set_id!=-1");
		
		$api = $this->ipsclass->load_class(ROOT_PATH."/sources/api/api_skins.php","api_skins");
		$api->skin_add_bits(ROOT_PATH."sources/market/install/mod_skin.xml");
		
		$this->ipsclass->admin->redirect($this->ipsclass->form_code_js."&code=database&do=recache&file=upskin","Inserting data into the skin cache is done<br />Moving on to caching the skin...");
	}

	function update_skin_cache()
	{
		$this->ipsclass->input['lastset'] = intval($this->ipsclass->input['lastset']);
		
		$api = $this->ipsclass->load_class(ROOT_PATH."/sources/api/api_skins.php","api_skins");
		$skin = $api->skin_rebuild_caches($this->ipsclass->input['lastset']);
		
		if ( $skin['completed'] )
		{
			$this->ipsclass->admin->redirect( $this->ipsclass->form_code_js."&code=database&do=recache&file=upskin&lastset={$skin['completed']}", "Rebuilt cache for skin set {$skin['set_name']}<br />Proceeding to the next skin..." );
		}
		
		$this->ipsclass->admin->redirect($this->ipsclass->form_code_js,"Updating the skin cache is done<br />Recache of the skin and language files done.<br />Reloading the ACP...");
	}
	
	function uninstall()
	{
		if (LIMIT_TO_ONLY_ROOT && $this->ipsclass->member['mgroup'] != $this->ipsclass->vars['admin_group'])
		{
			$this->ipsclass->admin->error("Sorry, this page is only for root admin only.");
		}
		
		$this->ipsclass->DB->sql_drop_table( 'market_versions'        );
		$this->ipsclass->DB->sql_drop_table( 'market_categories'      );
		$this->ipsclass->DB->sql_drop_table( 'market_items'           );
		$this->ipsclass->DB->sql_drop_table( 'market_inventory'       );
		$this->ipsclass->DB->sql_drop_table( 'market_buy_logs'        );
		$this->ipsclass->DB->sql_drop_table( 'market_item_logs'       );
		$this->ipsclass->DB->sql_drop_table( 'market_plugins'         );
		$this->ipsclass->DB->sql_drop_table( 'market_fee_logs'        );
		$this->ipsclass->DB->sql_drop_table( 'market_reward_logs'     );
		$this->ipsclass->DB->sql_drop_table( 'market_wages'           );
		$this->ipsclass->DB->sql_drop_table( 'market_wages_collected' );
		$this->ipsclass->DB->sql_drop_table( 'market_taxes'           );
		$this->ipsclass->DB->sql_drop_table( 'market_tax_logs'        );
		
		if($this->ipsclass->DB->field_exists("market_access", "members")) $this->ipsclass->DB->sql_drop_field('members','market_access');
		if($this->ipsclass->DB->field_exists("market_tax"   , "members")) $this->ipsclass->DB->sql_drop_field('members','market_tax'   );
		
		if($this->ipsclass->DB->field_exists("g_market_tax"     , "groups")) $this->ipsclass->DB->sql_drop_field('groups','g_market_tax'     );
		if($this->ipsclass->DB->field_exists("g_market_view"    , "groups")) $this->ipsclass->DB->sql_drop_field('groups','g_market_view'    );
		if($this->ipsclass->DB->field_exists("g_market_use"     , "groups")) $this->ipsclass->DB->sql_drop_field('groups','g_market_use'     );
		if($this->ipsclass->DB->field_exists("g_market_discount", "groups")) $this->ipsclass->DB->sql_drop_field('groups','g_market_discount');
		
		if($this->ipsclass->DB->field_exists("market_reply", "forums")) $this->ipsclass->DB->sql_drop_field('forums','market_reply');
		if($this->ipsclass->DB->field_exists("market_reply_amount", "forums")) $this->ipsclass->DB->sql_drop_field('forums','market_reply_amount');
		if($this->ipsclass->DB->field_exists("market_topic", "forums")) $this->ipsclass->DB->sql_drop_field('forums','market_topic');
		if($this->ipsclass->DB->field_exists("market_topic_amount", "forums")) $this->ipsclass->DB->sql_drop_field('forums','market_topic_amount');
		
		$settings_group = $this->ipsclass->DB->build_and_exec_query(array('select'=>'*','from'=>'conf_settings_titles','where'=>"conf_title_keyword='ibmarket'"));
		if($settings_group)
		{
			$this->ipsclass->DB->do_delete('conf_settings',"conf_group=".$settings_group['conf_title_id']);
			$this->ipsclass->DB->do_delete('conf_settings_titles',"conf_title_id=".$settings_group['conf_title_id']);
		}
		
		$this->ipsclass->DB->do_delete('task_manager',"task_key='market'");
		
		$this->ipsclass->DB->do_delete('components',"com_section='market'");
		
		$this->ipsclass->cache['settings'] = array();
		
		$this->ipsclass->DB->simple_construct( array( 'select' => '*', 'from' => 'conf_settings', 'where' => 'conf_add_cache=1' ) );
		$info = $this->ipsclass->DB->simple_exec();
		
		while ( $r = $this->ipsclass->DB->fetch_row($info) )
		{
			$value = $r['conf_value'] != "" ?  $r['conf_value'] : $r['conf_default'];
			
			if ( $value == '{blank}' )
			{
				$value = '';
			}
			
			$this->ipsclass->cache['settings'][ $r['conf_key'] ] = $value;
		}
		
		$this->ipsclass->update_cache( array( 'name' => 'settings', 'array' => 1, 'deletefirst' => 1 ) );
		
		require_once( ROOT_PATH.'sources/action_admin/components.php' );
		$components           = new ad_components();
		$components->ipsclass =& $this->ipsclass;
		
		$components->components_rebuildcache();
		
		$this->ipsclass->admin->save_log("ibMarket: Uninstalled");
		
		$this->ipsclass->admin->redirect($this->ipsclass->base_url,"Uninstalling ibMarket done...");
	}
}
?>